//
//  MineViewController.m
//  BreadTravel
//
//  Created by 张健 on 15/12/22.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
//

#import "MineViewController.h"
#import "ZJRegisterViewController.h"
#import "ZJLoginViewController.h"
#import "DataBase.h"
#import "CollectCityViewController.h"
@interface MineViewController ()<UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property(nonatomic,strong)UITableView *myTableView;

@end

@implementation MineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(150, 15, 50, 20)];
    titleLabel.text = @"我的";
    titleLabel.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = titleLabel;
    
    [[DataBase shareDataBase] openDB];
    
    NSString *string = [[NSUserDefaults standardUserDefaults]objectForKey:@"state"];
    NSString *name = @"";
    if ([string isEqualToString:@"1"]) {
        name = @"注销";
    }else{
        name = @"登陆";
    }
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:name style:UIBarButtonItemStyleDone target:self action:@selector(rightAction:)];
    
    
    self.myTableView = [[UITableView alloc]initWithFrame:[[UIScreen mainScreen] bounds] style:UITableViewStyleGrouped];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    [self.view addSubview:self.myTableView];
    [self.myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    
}
#pragma mark 页面显示的时候,根据状态值,判断按钮的文字,和点击实现对应的方法
-(void)viewWillAppear:(BOOL)animated{
    
    NSString *state = [[NSUserDefaults standardUserDefaults]objectForKey:@"state"];
    NSLog(@"%@",state);
    
    if ([state isEqualToString:@"0"]) {
        self.navigationItem.rightBarButtonItem.title = @"登陆";
        ZJLoginViewController *loginVC = [[ZJLoginViewController alloc]init];
        [self presentViewController:loginVC animated:YES completion:^{
            
        }];
    }else{
        
        self.navigationItem.rightBarButtonItem.title = @"注销";
    }
}

#pragma mark 右上角按钮
- (void)rightAction:(UIBarButtonItem *)bar{
    
    NSString *string = [[NSUserDefaults standardUserDefaults]objectForKey:@"state"];
    if ([string isEqualToString:@"1"]) {
        [[NSUserDefaults standardUserDefaults]setObject:@"0" forKey:@"state"];
        self.navigationItem.rightBarButtonItem.title = @"登陆";
        
    }else{
        
        ZJLoginViewController *loginVC = [[ZJLoginViewController alloc]init];
        [self presentViewController:loginVC animated:YES completion:^{
            
        }];
    }
}

#pragma mark 区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 4;
}
#pragma mark 行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 1) {
        return 2;
    }else{
        return 1;
    }
}

#pragma mark cell没行的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellID = @"UITableViewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    
    if (indexPath.section == 0) {
        
        cell.textLabel.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"user"];
//        NSMutableArray *array = [[DataBase shareDataBase]selectUserData:cell.textLabel.text];
//        MineUserModel *userModel = [array objectAtIndex:0];
//        NSData *imageData = [NSData dataWithData:userModel.data];
////        NSLog(@"%@",imageData);
//        UIImage *image = [UIImage imageWithData: imageData];
//        cell.imageView.image = image;
        
        
    }else if (indexPath.section == 1 && indexPath.row == 0) {
        
        cell.textLabel.text = @"相册";
        cell.imageView.image = [UIImage imageNamed:@"MoreMyAlbum"];
        
    }else if (indexPath.section == 1 && indexPath.row == 1){
        
        cell.textLabel.text = @"收藏";
        cell.imageView.image = [UIImage imageNamed:@"MoreMyFavorites"];
        
    }else if (indexPath.section == 2){
        cell.imageView.image = [UIImage imageNamed:@"iconfont-yejianmoshi"];
        cell.textLabel.text = @"夜间模式";
        
    }else{
        cell.textLabel.text = @"清除缓存";
        cell.imageView.image = [UIImage imageNamed:@"iconfont-zhuanyeqingji"];
    }
    return cell;
}
#pragma mark 点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        
        
        
    }else if (indexPath.section == 1 && indexPath.row == 0) {
        
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.allowsEditing = YES;
        picker.delegate = self;
        [self presentViewController:picker animated:YES completion:^{
            
        }];
    }else if (indexPath.section == 1 && indexPath.row == 1){
        
        CollectCityViewController *colectVC = [[CollectCityViewController alloc]init];
        [self.navigationController pushViewController:colectVC animated:YES];
    }else if (indexPath.section == 2){
        
        
        
    }else{
        
        [self rightAction];
    }
    
}

//到系统相册
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark - 清除缓存的方法,调用一下就行了
-(void)rightAction
{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    
    float fSize = [self folderSizeAtPath:path];
    NSLog(@"fSize = %f",fSize);
    
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"是否清除缓存" message:[NSString stringWithFormat:@"缓存大小为%.2f", fSize] preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alertC animated:YES completion:^{
        
        
    }];
    
    //创建提示框按钮
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSLog(@"点击的是确定按钮");
        
        [self clearCacheFlies];
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        //显示的文字
        hud.labelText = @"清除缓存成功";
        //是否有遮罩
        hud.dimBackground = NO;
        hud.labelFont = [UIFont boldSystemFontOfSize:22];
        hud.backgroundColor = [UIColor clearColor];
        //提示框的样式
        hud.mode = MBProgressHUDModeCustomView;
        [hud show:YES];
        //两秒之后隐藏
        [hud hide:YES afterDelay:2];
        
        
    }];
    //将按钮放在提示框上
    [alertC addAction:action];
    
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        NSLog(@"点击的是取消按钮");
        
    }];
    [alertC addAction:action1];
    
    
    
    //    self.navigationItem.leftBarButtonItem.title = @"全部";
    //    self.tableView.contentOffset = CGPointMake(0, 0);
    //
    //    [self getData];
}



/*整个目录的文件大小*/
//遍历文件夹获得文件夹大小，返回多少M
-(float)folderSizeAtPath:(NSString *) folderPath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if (![manager fileExistsAtPath:folderPath])
    {
        return 0;
    }
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    
    NSString* fileName;
    
    long long folderSize = 0;
    
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    //获取SDWebImage缓存图片大小
    NSUInteger size = [[SDImageCache sharedImageCache] getSize];
    
    //清空缓存
    [[SDImageCache sharedImageCache] cleanDisk];
    
    //字节转成 兆        字节    kb      兆/mb
    float cacheSize = size / 1024.0 / 1024.0;
    NSLog(@"缓存大小为%.2f", cacheSize);
    
    float aaaaaaaa = folderSize + cacheSize;
    
    return aaaaaaaa/(1024.0*1024.0);
}

- (long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if([manager fileExistsAtPath:filePath]){
        //获取文件属性,根据属性计算大小
        return[[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

//一、清理缓存Document文件夹，删除文件方法
-(void)clearCacheFlies{
    
    //    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    //获得document下的所有子文件夹
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
    NSLog(@"files :%ld",[files count]);
    NSLog(@"files :%@",files);
    
    for (NSString *p in files) {
        NSError *error;
        NSString *path = [cachPath stringByAppendingPathComponent:p];
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
        }
        NSLog(@"清理成功！");
    }
    [[SDImageCache sharedImageCache] cleanDisk];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
